package gxdlxy.zx2201.chat5;

public class Example3 {
    public static void main(String[] args) {
        int i, j;
        String str = "The setting sun is reflected from the windows of the alms-house as " +
                "brightly as from the rich man's abode; the snow melts before its door as " +
                "early in the spring. I do not see but a quiet mind may live as contentedly " +
                "there, and have as cheering thoughts, as in a palace. The town's poor seem " +
                "to me often to live the most independent lives of any. May be they are simply " +
                "great enough to receive without misgiving. Most think that they are above being " +
                "supported by the town; but it often happens that they are not above supporting " +
                "themselves by dishonest means. Which should be more disreputable. Cultivate " +
                "poverty like a garden herb, like sage.";
        System.out.println("原文: " + str);
        // 1 单词的数量;
        int wordCount = str.split(" ").length;
        System.out.println("单词数量: " + wordCount);
        // 2 每个字母出现的次数（不区分大小写，其他字符不需要统计）
        str = str.toLowerCase();
        char[] chars = str.toCharArray();
        int[] letterCount = new int[26];
        for (i = 0; i < chars.length; i++)
            if (chars[i] >= 'a' && chars[i] <= 'z')
                letterCount[chars[i] - 'a']++;
        for (i = 0; i < letterCount.length; i++) {
            System.out.print((char) (i + 'a') + " count:" + letterCount[i] + "\t");
            if ((i + 1) % 5 == 0)
                System.out.println();
        }
        System.out.println();
        // 3 每个单词出现的次数（不区分大小写）
        // 移除非字母和空格字符，移除后的结果存到StringBuffer
        StringBuffer strBuf = new StringBuffer();
        for (i = 0; i < chars.length; i++)
            if (chars[i] >= 'a' && chars[i] <= 'z' || chars[i] == ' ')
                strBuf.append(chars[i]);
        str = strBuf.toString();

        String[] words = str.split(" ");
        // 去除重复的单词
        String[] wordDiff = new String[words.length]; // 用来存储去除重复后的单词数组
        wordCount = 0;
        for (i = 0; i < words.length; i++) {
            for (j = 0; j < wordCount; j++)
                if (words[i].equals(wordDiff[j]))
                    break;
            if (j == wordCount)
                wordDiff[wordCount++] = words[i];
        }
        // 开始单词计数
        int[] wordCnt = new int[wordCount];
        for (i = 0; i < words.length; i++)
            for (j = 0; j < wordCount; j++)
                if (words[i].equals(wordDiff[j])) {
                    wordCnt[j]++;
                    break;
                }
        // 输出结果
        for (i = 0; i < wordCount; i++) {
            System.out.print(wordDiff[i] + ":" + wordCnt[i] + "\t");
            if ((i + 1) % 5 == 0)
                System.out.println();
        }
    }
}
